<?php
/**
 * Project: AIGC
 * Author: moufer <moufer@163.com>
 * Date: 2024/7/27 00:51
 */

namespace module\chat\model;

use module\user\library\interface\FavoriteInterface;
use mof\Model;
use think\model\relation\BelongsTo;

class Role extends Model implements FavoriteInterface
{
    protected $name = 'chat_role';

    protected $type = [
        'icon'   => 'storage',
        'config' => 'json'
    ];

    protected array $searchFields = [
        'category_id' => 'integer',
        'type'        => 'string',
        'status'      => ['integer', 'zero' => 0],
        'name'        => ['string', 'op' => 'like'],
    ];

    public function category(): BelongsTo
    {
        return $this->belongsTo(Category::class, 'category_id')
            ->visible(['id', 'pid', 'name', 'icon']);
    }

    public function sourceId(): int
    {
        return $this->getAttr('id');
    }

    public function sourceType(): string
    {
        return 'chat:role';
    }

    public function sourceFields(): array
    {
        return [
            'id', 'category_id', 'name', 'icon', 'intro', 'favor_ct', 'used_ct'
        ];
    }

    public function updateFavoriteCount($num = 1): void
    {
        $key = 'favor_ct';
        $fun = 'inc';
        if ($num < 0) {
            $fun = 'dec';
            $num = abs($this->getAttr($key) > $num ? $num : $this->getAttr($key));
        }
        $this->$fun($key, $num)->save();
    }
}